<?php

namespace App\Http\Controllers\Web\Buyer;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use App\Repository\Models\Carts;
use App\Repository\Models\Products;
use App\Repository\Models\ProductSkus;
use App\Repository\Repositories\Interfaces\CartsRepository;
use App\Repository\Repositories\Interfaces\CompanyRepository;
use App\Repository\Repositories\Interfaces\ExpressCompanyRepository;
use App\Repository\Repositories\Interfaces\ProductSkusRepository;
use App\Repository\Repositories\Interfaces\ShopRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

/**
 * 购物车管理控制器
 *
 * @package App\Http\Controllers\Backend
 */
class CartsController extends BaseController
{
    /**
     * @var CartsRepository
     */
    protected $carts_repo;
    protected $user_id;

    public function __construct(CartsRepository $carts_repo)
    {
        parent::__construct();
        $this->carts_repo = $carts_repo;
        $this->user_id = array_get($this->user, 'id');

        //用户只能操作自身所属数据
        $this->carts_repo->scopeQuery(function ($query) {
            return $query->where('user_id', $this->user_id);
        });
    }

    public function index(Request $request, ShopRepository $company_repo)
    {
        $type = $request->get('type', 'group_by_shops');
        if($type == 'group_by_shops'){  //根据是否失效、商铺分组
            //有效购物车列表
            $valid_shops = $this->getCarts($company_repo, function ($query) {
                $query->where(['status' => Products::STATUS_CHECKED, 'is_for_sale' => Products::IS_FOR_SALE_YES]);
            });

            //已失效的购物车列表
            $invalid_shops = $this->getCarts($company_repo, function ($query) {
                $query->where('status', '!=', Products::STATUS_CHECKED)->orWhere('is_for_sale', '!=', Products::IS_FOR_SALE_YES);
            });

            return $this->success(ErrorConst::SUCCESS_CODE, ['valid_list' => $valid_shops, 'invalid_list' => $invalid_shops]);
        }elseif($type == 'all'){  //直接返回全部数据
            $carts = $this->carts_repo->orderBy('created_at', 'desc')->all(['id', 'user_id', 'shop_id', 'product_id', 'sku_id', 'num']);
            return $this->success(ErrorConst::SUCCESS_CODE, $carts['data']);
        }
    }

    public function show($id)
    {
        //购物车商品无详情
    }

    public function store(Request $request, ProductSkusRepository $product_skus_repo)
    {
        $this->validate($request, [
            'sku_id' => 'required|integer',
            'num' => 'required|integer',
        ], [
            'sku_id.required' => 'SKU ID不能为空',
            'sku_id.exists' => 'SKU ID必须为整型',
            'num.required' => '商品数量不能为空',
            'num.integer' => '商品数量必须为整型'
        ]);
        $data = $request->all(['sku_id', 'num']);

        $product_sku = $product_skus_repo->with(['product'])->find($data['sku_id']);
        $product = $product_sku['data']['product'];

        //如果SKU存在，不存在对应商品，也视为无效
        if (!$product) {
            return $this->error(ErrorConst::NO_DATA_CODE, ErrorConst::NO_DATA_CODE_MSG);
        }

        $data['product_id'] = array_get($product, 'id');
        $data['shop_id'] = array_get($product, 'shop_id');
        $data['status'] = array_get($product, 'status') ? Carts::STATUS_VALID : Carts::STATUS_INVALID;
        $data['user_id'] = $this->user_id;

        $ret = $this->carts_repo->updateOrCreateCart($data);

        return $this->noDataReturn($ret ? true : false);
    }

    public function update(Request $request, $id)
    {
        //更新交由store负责，相当于updateOrCreate
    }

    public function delete($id)
    {
        $ret = $this->carts_repo->delete($id);
        return $this->noDataReturn($ret ? true : false);
    }

    public function batchDelete(Request $request)
    {
        $this->validate($request, [
            'type' => 'in:all,batch',
            'cart_ids' => 'array',
        ], [
            'type.in' => '所传参数不在范围内',
            'cart_ids' => 'cart_ids必须为数组'
        ]);
        $data = $request->all(['type', 'cart_ids']);
        //@todo $data['user_id'] = Auth::user()->id();

        if (array_get($data, 'type') == 'all') {
            $this->carts_repo->emptyCart();
        } else {
            $this->carts_repo->batchDelete(array_get($data, 'cart_ids', []));
        }

        $data=Carts::query()->where('user_id',$this->user_id)->get(['id', 'user_id', 'shop_id', 'product_id', 'sku_id', 'num'])->toArray();

        return $this->success(ErrorConst::SUCCESS_CODE_MSG, $data);
    }

    private function getCarts($company_repo, $closure)
    {
        //用户只能操作自身所属数据
        $this->carts_repo->scopeQuery(function ($query) {
            return $query->where('user_id', $this->user_id);
        });

        $carts = $this->carts_repo
            ->with(['product', 'sku'])
            ->orderBy('shop_id', 'asc')
            ->whereHas('product', $closure)
            ->all();

        //获取相关店铺
        $shop_ids = array_unique(array_column($carts['data'], 'shop_id'));
        //计算购物车商品数量
        $carts_count = count($carts['data']);
        $shops = $company_repo->findWhereIn('sp_id', $shop_ids, ['sp_id', 'sp_name']);

        //根据店铺进行分组
        foreach ($shops['data'] as $key => $shop) {
            $shops['data'][$key]['carts'] = array_filter($carts['data'], function ($val) use ($shop) {
                return $val['shop_id'] == $shop['sp_id'] ? true : false;
            });
        }

        return [
            'shops' => $shops['data'],
            'carts_count' => $carts_count
        ];
    }

    /**
     * 把cookie 数据库合并
     */
    public function add_carts(Request $request){
        $carts=$request->all();
        $data_carts=$this->carts_repo->all();
        $save_id=[];

        //有未登录前 cookie
        if(!empty($carts['data'])){
            if(!empty($data_carts)){
                foreach($data_carts['data'] as $k=>$v ){
                    $m=0;
                    $save_data['num']=$v['num'];
                    foreach($carts['data'] as $key=>$val){
                        if($v['sku_id']==$val['sku_id']){
                            $save_data['num']+=$val['num'];
                            $this->carts_repo->update($save_data,$v['id']);
                            $m=1;
                        }

                    }
                    if($m==1){
                        $save_id[]=$v['sku_id'];
                    }
                }
                foreach($carts['data'] as $k=>$v){
                    if(!in_array($v['sku_id'],$save_id)){
                        $v['user_id']=$this->user_id;
                        $this->carts_repo->create($v);
                    }
                }
            }else{
                foreach($carts['data'] as $k=>$v){
                    $v['user_id']=$this->user_id;
                    $this->carts_repo->create($v);
                }
            }

        }

        //取数据库购物车数据
//        $carts = $this->carts_repo->orderBy('created_at', 'desc')->all(['id', 'user_id','shop_id', 'product_id', 'sku_id', 'num', 'status']);
        $carts=Carts::query()->where('user_id',$this->user_id)->orderBy('created_at','desc')->get(['id', 'user_id','shop_id', 'product_id', 'sku_id', 'num', 'status'])->toArray();

        return $this->success(ErrorConst::SUCCESS_CODE, $carts);
    }

    /**
     * 获取cookie购物车数据
     */
    public function get_carts(CompanyRepository $company_repo,Request $request)
    {
        $carts_arr=$request->all();
        //有效购物车列表
        $valid_shops = $this->getCookieCarts($company_repo, $carts_arr);
        return $this->success(ErrorConst::SUCCESS_CODE,  $valid_shops);
    }

    /**
     * 获取cookie购物车数据
     */
    private function getCookieCarts($company_repo,$carts_arr)
    {
        $product_id = array_unique(array_column($carts_arr, 'product_id'));
        $carts=Products::query()->where('status' , Products::STATUS_CHECKED)->where('is_for_sale', Products::IS_FOR_SALE_YES)->whereIn('id',$product_id)->orderBy('shop_id', 'asc')->get()->toArray();//['id','name','shop_id','unit','images']

        //获取相关店铺
        $shop_ids = array_unique(array_column($carts,'shop_id'));
        //计算购物车商品数量
        $carts_count = count($shop_ids);
        $shops = $company_repo->findWhereIn('id', $shop_ids, ['id', 'company_name']);

//        //根据店铺进行分组
        foreach ($shops['data'] as $key => $shop) {
            $shops['data'][$key]['carts'] = array_filter($carts, function ($val) use ($shop) {
                return $val['shop_id'] == $shop['id'] ? true : false;
            });
        }

        //处理数据
        foreach($shops['data'][0]['carts'] as $k =>$v){
            $arr_data=$v;
            unset($shops['data'][0]['carts'][$k]);
            $arr_skus=ProductSkus::query()->find($carts_arr[$k]['sku_id']);
            $shops['data'][0]['carts'][]=[
                'shop_id'=>$carts_arr[$k]['shop_id'],
                'product_id'=>$carts_arr[$k]['product_id'],
                'sku_id'=>$carts_arr[$k]['sku_id'],
                'num'=>$carts_arr[$k]['num'],
                'status'=>$carts_arr[$k]['status'],
                'type'=>$carts_arr[$k]['type'],
                'product'=>$arr_data,
                'sku'=>$arr_skus,
            ];
        }

        return [
            'valid_shops' => $shops['data'],
            'valid_count' => $carts_count
        ];
    }


    /**
     * @return \Illuminate\Support\Collection
     * 重置购物车后 获取购物车数据库
     */
    public function fresh_get(){
        $data=Carts::query()->where('user_id',$this->user_id)->get(['id', 'user_id', 'shop_id', 'product_id', 'sku_id', 'num'])->toArray();
        return $this->success(ErrorConst::SUCCESS_CODE,  $data);

    }
}
